/*
 * gx_log.c
 *
 *  Created on: 2012-4-1
 *      Author: zhanggx
 */
#include <stdarg.h>

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/time.h>
#include <time.h>
#include <unistd.h>

#include "gx.h"


static const char* maplevel[] = {
			"TRACE",
			"DEBUG",
			"NOTICE",
			"WARNING",
			"ERROR"
			};

static const char* level2str(int level) {
	if (level > GX_LOG_ERROR || level < GX_LOG_TRACE)
		return "Unknown";
	else
		return maplevel[level];
}

int gx_set_log_file(const char* path){
	int logfd;

	int log_file_mode = O_CREAT | O_APPEND | O_WRONLY;
	logfd = open(path, log_file_mode, 0644);
	if (logfd == -1) {
		perror("open");
		GX_ERROR_LOG("can't open file to log %s", path);
		return logfd;
	}
	gx_string_t log_head = gx_new_string("***************open log******************\n");
	write(logfd, log_head.buf, log_head.len);
	gx_globals.g_log->filefd = logfd;
	gx_globals.g_log->log_path = path;
	gx_globals.g_log->f_fp = fdopen(gx_globals.g_log->filefd, "a");
	return 0;
}

void gx_set_log_level(int level) {
	if (level > GX_LOG_ERROR || level < GX_LOG_TRACE)
		return;
	gx_globals.g_log->log_level = level;
}

void gx_log(int log_level, const char* fmt,...) {
	va_list ap;
	if (log_level < gx_globals.g_log->log_level) {
		return;
	}

	if (gx_globals.g_log->f_fp) {
		struct timeval timeofday;
		gettimeofday(&timeofday, NULL);
		time_t now = timeofday.tv_sec;
		struct tm newtime;
		struct tm *date = localtime_r(&now, &newtime);
		pthread_mutex_lock(&(gx_globals.g_log->mutex));
		fprintf(gx_globals.g_log->f_fp, "[%s]", level2str(log_level));
		fprintf(gx_globals.g_log->f_fp, "[%02d-%02d %02d:%02d:%02d]",
				date->tm_mon + 1,
				date->tm_mday,
				date->tm_hour,
				date->tm_min,
				date->tm_sec);
		va_start(ap, fmt);
		vfprintf(gx_globals.g_log->f_fp, fmt, ap);
		pthread_mutex_unlock(&(gx_globals.g_log->mutex));
	}
	else{
		perror("fdopen");
	}

}
